<?php
	include_once('inc/connect2db.php');
	require_once('sdk/util.php');
	
	if ($_SERVER['REQUEST_METHOD'] === 'GET') {
		$method = "GET";
	} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		$method = "POST";
	}

	$raw_input = file_get_contents('php://input');
	
	$resolved_body = Util::resolveBody($raw_input);

	if (is_array($resolved_body)) {
		analyse_msg($resolved_body);
	} else {
		// 用于第一次验证 url
		echo $resolved_body;
	}
	
	// $request = json_encode($resolved_body);

	// $result = mysql_query("insert into `temp` (method, message) values ('$method', '$request')");

	// [{"at":1547393909797,"login_type":7,"type":2,"dev_id":514756493,"status":1},
	//  {"at":1547393986202,"type":1,"ds_id":"temperature","value":21.3,"dev_id":514756493}]
	function analyse_msg($msg) {
		$json = json_decode(json_encode((object) $msg), TRUE);
		//$data = $json["at"];
		
		if (isset($json["type"])) {
			if ($json["type"] == 2) {
				update_status($json["dev_id"], $json["status"], $json["at"]);			
			} else if ($json["type"] == 1) {
				update_temperature($json["dev_id"], $json["ds_id"], $json["value"], $json["at"]);
			}
		}
		
		// $result = mysql_query("insert into `temp` (method, message) values ('123', '$data')");
	}

	function update_status($device_id, $status, $at) {
		mysql_query("insert into `temperature_recorders` (`timestamp`, device_id, device_status) values (FROM_UNIXTIME($at / 1000), '$device_id', $status)");
	}

	function update_temperature($device_id, $datastream_id, $value, $at) {
		mysql_query("insert into `temperature_recorders` (temperature1, `timestamp`, device_id, datastream_id) values ('$value', FROM_UNIXTIME($at / 1000), '$device_id', '$datastream_id')");
	}
?>